import Vue from 'vue';
import Vuex from 'vuex';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { login, logout, getUserInfo } from '@/api/user';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
    }
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password })
          .then(response => {
            const { data } = response;
            commit('SET_TOKEN', data.token);
            setToken(data.token);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then(response => {
            const { data } = response;
            if (!data) {
              reject('获取用户信息失败，请重新登录');
            }
            commit('SET_USER_INFO', data);
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    
    // 登出
    logout({ commit }) {
      return new Promise((resolve) => {
        // 尝试调用登出接口
        logout()
          .then(() => {
            // 登出成功
            commit('SET_TOKEN', '');
            commit('SET_USER_INFO', {});
            removeToken();
            resolve();
          })
          .catch(() => {
            // 即使登出接口调用失败，也清除本地状态
            commit('SET_TOKEN', '');
            commit('SET_USER_INFO', {});
            removeToken();
            resolve();
          });
      });
    }
  },
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo,
    isTeacher: state => state.userInfo.role === 1,
    isAdmin: state => state.userInfo.role === 2,
    roles: state => {
      const roleArray = [];
      if (state.userInfo && state.userInfo.role !== undefined) {
        roleArray.push(state.userInfo.role);
      }
      return roleArray;
    }
  }
}); 